package com.tanhua.server.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.autoconfig.template.HuanXinTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.db.api.QuestionApi;
import com.tanhua.dubbo.db.api.UserInfoApi;
import com.tanhua.dubbo.mongo.api.*;
import com.tanhua.model.db.PageInfo;
import com.tanhua.model.db.Question;
import com.tanhua.model.db.User;
import com.tanhua.model.db.UserInfo;
import com.tanhua.model.mongo.RecommendUser;
import com.tanhua.model.mongo.UserLike;
import com.tanhua.model.mongo.Visitors;
import com.tanhua.model.vo.*;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import com.tanhua.server.interceptor.UserThreadLocal;
import org.apache.commons.lang3.RandomUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class TanhuaService {

    @DubboReference
    private RecommendUserApi recommendUserApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private QuestionApi questionApi;

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    @DubboReference
    private VisitorsApi visitorsApi;

    @DubboReference
    private UserLocationApi userLocationApi;

    @DubboReference
    private UserLikeApi userLikeApi;

    @DubboReference
    private FriendApi friendApi;

    @Autowired
    private MessagesService messagesService;

    @Autowired
    private RedisTemplate redisTemplate;

    //今日佳人
    public TodayBest todayBest() {

        //1.获取登录的用户id
        Long toUserId = UserHolder.getUserId();
        //调用recommendUserApi,查询匹配度最高的推荐今日最佳
        RecommendUser recommendUser = recommendUserApi.queryWithMaxScore(toUserId);
        //若查询出的匹配信息为空,构造假数据
        if (recommendUser == null) {
            recommendUser = new RecommendUser();
            recommendUser.setUserId(1l);
            recommendUser.setScore(95d);

        }
        //获得推荐今日最佳用户的id
        Long userId = recommendUser.getUserId();
        //获取该用户信息
        UserInfo userInfo = userInfoApi.findById(userId);

        //构造TodayBest对象 存入数据
        TodayBest todayBest = new TodayBest();

        //同名同属性 赋值过去
        BeanUtil.copyProperties(userInfo, todayBest);

        //不同属性的 再赋值
        todayBest.setTags(userInfo.getTags().split(","));
        todayBest.setFateValue(recommendUser.getScore().longValue());

        return todayBest;
    }

    //推荐朋友 --首页推荐
    /*public PageResult recommendation(RecommendUserDto dto) {

        //获取登录的用户id
        Long toUserId = UserHolder.getUserId();
        //根据toUserId 获取RecommendUser的list
        List<RecommendUser> recommendUserlist =
                recommendUserApi.queryRecommendUserlist(toUserId, dto.getPage(), dto.getPagesize());

        if (recommendUserlist==null || recommendUserlist.size()<0){
            recommendUserlist=defaultList();
        }

        //根据每一个recommendUser对象获得一个UserInfo对象
        List<TodayBest> todayBests = new ArrayList<>();
        for (RecommendUser recommendUser : recommendUserlist) {

            UserInfo userInfo = userInfoApi.findById(recommendUser.getUserId());

            TodayBest init = TodayBest.init(userInfo, recommendUser);
            todayBests.add(init);

        }

        PageResult pageResult = new PageResult();
        pageResult.setItems(todayBests);
        pageResult.setPage(dto.getPage());
        pageResult.setPagesize(dto.getPagesize());
        pageResult.setCounts(0l);

        return pageResult;
    }*/

    public PageResult recommendation(RecommendUserDto dto) {

        //获取登录的用户id
        Long toUserId = UserHolder.getUserId();
        //根据toUserId 获取RecommendUser的list
        List<RecommendUser> recommendUserlist =
                recommendUserApi.queryRecommendUserlist(toUserId, dto.getPage(), dto.getPagesize());

        if (recommendUserlist == null || recommendUserlist.size() < 0) {
            recommendUserlist = defaultList();
        }
        //提取所有list集合中对象的id
        List<Long> userIds = CollUtil.getFieldValues(recommendUserlist, "userId", Long.class);

        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds);
        List<TodayBest> listVo = new ArrayList<>();

        for (RecommendUser recommendUser : recommendUserlist) {

            Long userId = recommendUser.getUserId();
            UserInfo userInfo = map.get(userId);
            TodayBest vo = TodayBest.init(userInfo, recommendUser);
            listVo.add(vo);
        }


        return new PageResult(dto.getPage(), dto.getPagesize(), 0l, listVo);
    }

    public List<RecommendUser> defaultList() {
        List<RecommendUser> list = new ArrayList<>();
        for (int i = 0; i < 10; i++) {

            RecommendUser recommendUser = new RecommendUser();
            recommendUser.setUserId(i + 1l);
            recommendUser.setScore(i + 80d);
            list.add(recommendUser);
        }

        return list;
    }

    // 佳人信息 根据佳人信息查询
    public TodayBest personalInfo(Long userId) {

        //根据佳人id查询用户信息
        UserInfo userInfo = userInfoApi.findById(userId);

        //根据佳人id和本人id查询相似度值
        Long toUserId = UserHolder.getUserId();
        RecommendUser re = recommendUserApi.queryByUserId(userId, toUserId);

        //将我访问佳人的信息 添加到visitors表中
            //创建对象
        Visitors visitors=new Visitors();
        visitors.setUserId(userId);
        visitors.setVisitorUserId(toUserId);
        visitors.setDate(System.currentTimeMillis());
        visitors.setVisitDate(new SimpleDateFormat("yyMMdd").format(new Date()));
        visitors.setFrom("首页");
        visitors.setScore(re.getScore());
        visitorsApi.save(visitors);


        //构造值 返回
        return TodayBest.init(userInfo, re);
    }

    //查询陌生人问题
    public String strangerQuestions(Long userId) {

        Question question = questionApi.findByUserId(userId);

        return question == null ?"你的梦想是什么":question.getTxt ();
    }

    //回复陌生人问题
    public void reply(String reply, Long friendId) {

        Long userId = UserHolder.getUserId();
        Map map = new HashMap();
        map.put("userId", userId);
        map.put("huanXinId", "hx" + userId);
        UserInfo userInfo = userInfoApi.findById(userId);
        map.put("nickname", userInfo.getNickname());
        String questions = strangerQuestions(friendId);
        map.put("strangerQuestion", questions);
        map.put("reply", reply);


        String json = JSON.toJSONString(map);
        huanXinTemplate.sendMsg("hx" + friendId, json);

    }

    //搜附近
    public List<NearUserVo> search(String gender, String distance) {

        //1.获取userId
        Long userId = UserHolder.getUserId();

        //2.根据userId,distance 获得附近人的ids
        List<Long> ids = userLocationApi.search(userId, Long.valueOf(distance));

        //若没有数据则返回一个空集合
        if (ids == null ||ids.size()<=0) {
            return new ArrayList<>();
        }

        //3根据ids获得userinfo信息
        Map<Long, UserInfo> map = userInfoApi.findByIds(ids);

        //4.一个UserInfo构造一个NearUserVo对象
        List<NearUserVo> vos = new ArrayList<>();

        for (Long id : ids) {

            //把自己筛选出去
            if (id == userId) {
                continue;//跳过
            }
            UserInfo userInfo = map.get(id);
            //筛选性别
            if (!StringUtils.isEmpty(gender) && !gender.equals(userInfo.getGender())) {
                continue;//跳过
            }
            NearUserVo vo = NearUserVo.init(userInfo);
            vos.add(vo);

        }
        return vos;
    }

    //查询
    public List<CardVo> cards() {
        Long userId = UserHolder.getUserId();
        List<RecommendUser> records = recommendUserApi.queryRecommendUserlist(userId, 1, 50);
        if (records == null || records.size() <= 0) {
            records = defaultList();
        }
        List<Long> userIds = CollUtil.getFieldValues(records, "userId", Long.class);
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds);
        List<UserLike> userLikes = userLikeApi.findByUserId(userId);
        List<CardVo> vos = new ArrayList<>();
        List<Long> likeUserId = CollUtil.getFieldValues(userLikes, "likeUserId", Long.class);
        Iterator<Long> iterator = map.keySet().iterator();
        //已经喜欢或不喜欢的用户不再展示
        while (iterator.hasNext()){
            //是否包含 包含删除
            if (likeUserId.contains(iterator.next())){
                iterator.remove();
            }
        }
        //封装到cardvo
        for (UserInfo userInfo : map.values()){
            CardVo vo = CardVo.init(userInfo);
            vos.add(vo);
        }
        if (vos.size()<=2){
            List<RecommendUser> list = defaultList();
            List<Long> userIds1 = CollUtil.getFieldValues(list, "userId", Long.class);
            Map<Long, UserInfo> map1 = userInfoApi.findByIds(userIds1);
            for (UserInfo userInfo : map1.values()){
                CardVo vo = CardVo.init(userInfo);
                vos.add(vo);
            }
        }
        return vos;
    }

    //喜欢
    public void likeUser(Long likeUserId) {
        Long userId = UserHolder.getUserId();
        Boolean isLike = true;
        UserLike userLike = userLikeApi.findById(userId,likeUserId);
        if(userLike==null){
            //新建
            UserLike userLike1 = new UserLike();
            userLike1.setIsLike(isLike);
            userLike1.setUserId(userId);
            userLike1.setLikeUserId(likeUserId);
            userLikeApi.save(userLike1,isLike);
        }else {
            //修改状态
            UserLike userLike1 = new UserLike();
            userLike1.setIsLike(isLike);
            userLike1.setUserId(userId);
            userLike1.setLikeUserId(likeUserId);
            userLikeApi.update(userLike,isLike);
        }
        //互相喜欢加为好友
        boolean mutualLike = userLikeApi.isMutualLike(userId, likeUserId);
        if (mutualLike){
            friendApi.save(userId,likeUserId);
        }
        huanXinTemplate.addContact("hx"+userId,"hx"+likeUserId);
    }

    //不喜欢
    public void disLikeUser(Long likeUserId) {
        Long userId = UserHolder.getUserId();
        Boolean isLike = false;
        Boolean exists = userLikeApi.findExists(userId, likeUserId);
        if(!exists){
           //新建
           UserLike userLike1 = new UserLike();
           userLike1.setIsLike(isLike);
           userLike1.setUserId(userId);
           userLike1.setLikeUserId(likeUserId);
           userLikeApi.save(userLike1,isLike);
        }else {
           //修改状态
            UserLike userLike1 = new UserLike();
            userLike1.setIsLike(isLike);
            userLike1.setUserId(userId);
            userLike1.setLikeUserId(likeUserId);
           userLikeApi.update(userLike1,isLike);
        }
        huanXinTemplate.deleteContact("hx"+userId,"hx"+likeUserId);
    }
}
